#  -*- coding: utf-8 -*-
# __author__ = 'Administrator'
import os,threading,time
import datetime as dt
from dbservice.DBservice import DBService
class Timer_tool(object):
    '''
        定时任务脚本
    '''
    def __init__(self):
        # self.curTime = time.strftime("%Y-%m-%d", time.localtime())  # 记录当前时间
        self.execF = False
        self.ncount = 0
        self.curTime=self.timer_time()                    # 记录更新时间时间
    conn=DBService()

    def timer_time(self):
        '''
        设置定时时间
        :return: 返回定时时间
        '''
        now_time = dt.date.today()                       # 获取现在时间(时间日期格式)
        next_time = now_time + dt.timedelta(days=+1)     # 获取明天时间
        next_year = next_time.year                       # 获取年
        next_month = next_time.month                     # 月
        next_day = next_time.day                         # 日
        next_time_se = dt.datetime.strptime(
            str(next_year) + "-" + str(next_month) + "-" + str(next_day) + " 07:00:00", "%Y-%m-%d %H:%M:%S")      # 获取明天7点时间
        # timer_start_time = (next_time_se - now_time).total_seconds() # 时间转秒
        return next_time_se.strftime("%Y-%m-%d %H:%M:%S")# 定时时间


    def execTask(self,func):
        '''
        # 具体任务执行内容
        :param func:  传递具体定时执行任务的函数
        :return:
        '''
        pass
        # print("execTask executed!")

    def timerTask(self):

        if self.execF is False:
            self.execTask(self.conn.pg_into_mysql_information())        # 判断任务是否执行过，没有执行就执行
            self.execF = True
        else:                                                           # 任务执行过，判断时间是否新的一天。如果是就执行任务
            desTime = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
            print(self.curTime,desTime)
            if desTime > self.curTime:
                self.execF = False                                      # 任务执行执行状态调整
                self.curTime = self.timer_time()                        # 任务时间调整
        # self.ncount = self.ncount + 1
        print(self.execF)
        global timer                                                    # 避免线程堆积
        timer = threading.Timer(5, self.timerTask)                      # 任务设置
        timer.start()                                                   # 执行任务

# if __name__ == "__main__":
#     aa = Timer_tool()
#     global timer
#     timer = threading.Timer(5, aa.timerTask)
#     timer.start()